﻿using System;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using LoveMusic.Models;
using System.Xml;
using System.Threading;
using System.Collections.Generic;
namespace LoveMusic.Helpers
{
    public static class WebHelper
    {
        /// <summary>
        /// Returns xml document ready for parsing
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="xmlDoc"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        public static XmlDocument load(string xml, XmlDocument xmlDoc, string url)
        {
            try
            {
                xmlDoc.Load(new StringReader(xml));
                return xmlDoc;
            }
            catch (WebException webE)
            {
                throw webE;
            }
            catch (Exception e)
            {
                return null;
            }
        }

        /// <summary>
        /// Get the xml 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        /// 
        public static string GetResponse(string url)
        {
            try
            {
                WebClient wc = new WebClient();
                wc.Headers.Add(HttpRequestHeader.AcceptEncoding, "gzip");

                //that solves the problem partially:
                wc.Proxy = null;

                wc.Encoding = System.Text.Encoding.UTF8;
                wc.Headers.Add("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.2; .NET CLR 1.0.3705;)");


                using (ICSharpCode.SharpZipLib.GZip.GZipInputStream stream = new ICSharpCode.SharpZipLib.GZip.GZipInputStream(wc.OpenRead(url)))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.TimeWrite(ex, "GetResponse url=" + url);
                return null;
            }
        }

        public static string GetNewUrl4Shared(string url)
        {
            string html = GetResponseStandard(url);

            try
            {
                string[] parts = html.Split(new string[] { "function startDownload(){\r\n    //document.downloadForm.submit();\r\n    window.location = \"" }, StringSplitOptions.None);
                string[] subParts = parts[1].Split(new string[] { "\";\r\n  }\r\n\r\n  function startPlayMedia(){\r\n" }, StringSplitOptions.None);
                return subParts[0];
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        /// <summary>
        /// Get the xml 
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public static string GetResponseStandard(string url)
        {
            try
            {
               
                WebClient wc = new WebClient();

                using (Stream stream = wc.OpenRead(url))
                {
                    using (StreamReader reader = new StreamReader(stream))
                    {
                        return reader.ReadToEnd();
                    }
                }
            }
            catch (Exception ex)
            {
                TraceLog.TimeWrite(ex, "GetResponse url=" + url);
                return null;
            }
        }

        public static string GetMiddleString(string input, string start, string end)
        {
            int posOfStart = input.IndexOf(start);
            input = input.Substring(posOfStart + 1, input.Length - posOfStart - 1);

            int posOfEnd = input.IndexOf(end);
            input = input.Remove(posOfEnd);
            //int posOfLength = posOfStart+posOfEnd;
            return input;
            //string[] parts = input.Split(new string[] { start }, StringSplitOptions.None);
            //parts = parts[1].Split(new string[] { end }, StringSplitOptions.None);
            //return parts[0];
        }

        public static string GetFirstMiddleString(string input, string start, string end)
        {
            string[] parts = input.Split(new string[] { start }, StringSplitOptions.None);
            parts = parts[1].Split(new string[] { end }, StringSplitOptions.None);
            return parts[0];
        }

        public static string RemoveTags(string str)
        {
            return Regex.Replace(str, @"<(.|\n)*?>", string.Empty);
        }

        public static string RemoveSpecialCharacters(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c == ' ') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static string RemoveSpecialCharactersExceptAmpersand(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c == ' ') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c=='&')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static string RemoveSpecialCharactersExceptTire(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c == ' ') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == '-')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static string RemoveSpecialCharactersExceptComma(string str)
        {
            StringBuilder sb = new StringBuilder();
            foreach (char c in str)
            {
                if ((c == ' ') || (c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || c == '_' || c == ',')
                {
                    sb.Append(c);
                }
            }
            return sb.ToString();
        }

        public static string RemoveDigits(string key)
        {
            return Regex.Replace(key, @"\d", "");
        }

        public static void SubmitBot(string songTitle, int storyCategoryId, string storyDescription, string artistName)
        {
            string encodingCode = string.Empty;
            string tags = string.Empty;
            string videoID = string.Empty;
            string imageURL = string.Empty;
            string youTubeDescrption = string.Empty;
            bool hasImage = false;

            using (ModelDataContext db = new ModelDataContext())
            {
                try
                {
                    YouTubeApi youTube = new YouTubeApi();
                    Mp3FileApi mp3FileApi = new Mp3FileApi();
                    youTube.GetYouTubeVideo(songTitle, artistName, ref encodingCode, ref videoID, ref tags, ref youTubeDescrption);

                    //string[] tagz = tags.Split(new string[] { "," }, StringSplitOptions.None);
                    //foreach (string tagce in tagz)
                    //{
                    //    tag
                    //}  Who I Am
                    if (!db.StoryExists(songTitle, artistName))
                        db.SubmitStoryBot(songTitle, artistName, storyCategoryId, storyDescription, tags, mp3FileApi.GetMp3Urls(artistName, songTitle), videoID, new Guid("1685CC87-BA2F-450B-BBE6-2F81A0F149A9"), youTubeDescrption);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(ex.Message);
                }
            }

        }
        /// <summary>
        /// New SubmitBot for the purposes of the artist
        /// </summary>
        /// <param name="songTitle"></param>
        /// <param name="storyCategoryId"></param>
        /// <param name="storyDescription"></param>
        /// <param name="artistName"></param>
        public static void SubmitBotArtist(string songTitle, int storyCategoryId, string storyDescription, string artistName)
        {
            string encodingCode = string.Empty;
            string tags = string.Empty;
            string videoID = string.Empty;
            string imageURL = string.Empty;
            string youTubeDescrption = string.Empty;
            bool hasImage = false;

            using (ModelDataContext db = new ModelDataContext())
            {
                try
                {
                    YouTubeApi youTube = new YouTubeApi();
                    Mp3FileApi mp3FileApi = new Mp3FileApi();
                    youTube.GetYouTubeVideo(songTitle, artistName, ref encodingCode, ref videoID, ref tags, ref youTubeDescrption);

                    if (!db.StoryExists(songTitle, artistName))
                        db.SubmitStoryBotArtist(songTitle, artistName, storyCategoryId, storyDescription, tags, mp3FileApi.GetMp3Urls(artistName, songTitle), encodingCode, videoID, imageURL, hasImage, new Guid("86A13EB9-9CFB-414C-9C12-A580934E86E6"), youTubeDescrption);
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(ex.Message);
                }
            }

        }

        /// <summary>
        /// Cut the string if it is bigger than the number of characters in cut.
        /// </summary>
        /// <param name="input"></param>
        /// <param name="cut"></param>
        /// <returns></returns>
        public static string CutString(string input, int cut)
        {
            if (input != null)
            {
                if (input.Length > cut)
                    return input.Remove(cut);
                else
                    return input;
            }
            else
                return input;
        }


        public static string[] SplitString(string input, string delimiter)
        {
            if (input==null || input == string.Empty)
                return null;
            else
                return input.Split(new string[] { delimiter }, StringSplitOptions.None);
        }

        public static int GetRandomNumber(int start, int end)
        {
            System.Random RandNum = new System.Random();
            return RandNum.Next(start, end);
        }

        

        public static string CreateAmper(string input)
        {
            return input.Replace("&amp;", "&");
        }

        public static string RemoveDuplicates(string tags)
        {
            tags = tags.ToLower();
            string returnTag = string.Empty;
            string[] tagz = SplitString(tags,",");

            tagz = RemoveDuplicates(tagz);
            foreach (string tagy in tagz)
            {
                returnTag = tagy + "," + returnTag;
            }
            returnTag = returnTag.TrimEnd(',');
            return returnTag;
        }

        private static string[] RemoveDuplicates(string[] s)
        {
            HashSet<string> set = new HashSet<string>(s);
            string[] result = new string[set.Count];
            set.CopyTo(result);
            return result;
        }
    }



}